<template>
	<view>
		<view style="height:1px;background-color:#e4e4e4">
			
		</view>
		<scroll-view scroll-y class="result-type">
				<view v-if="JSON.parse(JSON.stringify(list)).length" class="t-conversation-item-container" v-for="(item,index) in list"
					:key="index">
					<view class="t-conversation-item">
						<view class="avatar-box">
							<image class="t-conversation-item-avatar"
								:src="item.avatar">
							</image>
						</view>
						<view class="t-conversation-item-content">
							<view class="u-flex u-row-between u-p-l-20 u-p-r-20 u-p-b-30">
								<view class="tui-result-name">{{item.nick}}</view>
								<text
									class="tui-result-time">{{getHistoryChatTime(item.time * 1000,$i18n,lang)}}</text>
							</view>
							<!-- 图片数据 -->
						<MessageText :id="item.flow + '-' + item.ID" :translate="dicttext1" :msgid="id1"
								v-if="item.type === types.MSG_TEXT" style="margin-top:-30rpx"
								:data="handleTextMessageShowContext(item)" :messageData="item"></MessageText>
							<MessageImage :id="item.flow + '-' + item.ID"
								:imglist="imgList" v-if="item.type === types.MSG_IMAGE"
								:data="handleImageMessageShowContext(item)" :messageData="item"></MessageImage>
							<MessageVideo :id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_VIDEO"
								:data="handleVideoMessageShowContext(item)" :messageData="item" />
							<MessageAudio :id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_AUDIO"
								:data="handleAudioMessageShowContext(item)" :messageData="item" />
							<MessageFace :id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_FACE"
								:data="handleFaceMessageShowContext(item)" :messageData="item" />
							<MessageCustom :id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_CUSTOM"
								:data="handleCustomMessageShowContext(item)" :messageData="item" />
							<MessageMerger :id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_MERGER"
								:data="handleMergerMessageShowContext(item)" :messageData="item"
								@click="godetail(item)" />
							<MessageFile :data="handleFileMessageShowContext(item)" :item="item"
								:id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_FILE" />
						</view>
					</view>
				</view>
				<view class="empty-wrap" v-show="isEmpty">
					<u-empty :text="$t('chat.chat_search_no_data')" mode="list"></u-empty>
				</view>
			<view style="height:50rpx"></view>
		</scroll-view>
	</view>
</template>

<script>
	import timStorage from "../../../utils/tim-storage.js";
	import MessageText from "../../TUIChat/components/message-elements/message-text.vue";
	import MessageImage from "../../TUIChat/components/message-elements/message-image.vue"
	import MessageVideo from "../../TUIChat/components/message-elements/message-video.vue";
	import MessageAudio from "../../TUIChat/components/message-elements/message-audio.vue";
	import MessageFace from "../../TUIChat/components/message-elements/message-face.vue";
	import MessageCustom from "../../TUIChat/components/message-elements/message-custom.vue";
	import MessageSystem from "../../TUIChat/components/message-elements/message-system.vue";
	import MessageMerger from "../../TUIChat/components/message-elements/message-merger.vue";
	import MessageFile from "../../TUIChat/components/message-elements/message-file.vue";
	import {
		handleAvatar,
		handleTextMessageShowContext,
		handleImageMessageShowContext,
		handleVideoMessageShowContext,
		handleAudioMessageShowContext,
		handleFileMessageShowContext,
		handleFaceMessageShowContext,
		handleLocationMessageShowContext,
		handleMergerMessageShowContext,
		handleTipMessageShowContext,
		handleCustomMessageShowContext,
	} from "../../../utils/untis";
	import {
		getHistoryChatTime
	} from "@/utils/date.js";
	import {
		useI18n
	} from "vue-i18n";
	import httpInterceptor from '@/utils/http.interceptor2.js';
	export default {
		components: {
			MessageText,
			MessageImage,
			MessageVideo,
			MessageAudio,
			MessageFace,
			MessageCustom,
			MessageSystem,
			MessageMerger,
			MessageFile,
		},
		data() {
			return {
				conversationID: '',
				groupID: 0,
				type: '',
				keyword: '',
				list: [],
				messageList: [],
				groupMemberDict: [],
				swiperCurrent: 0,
				types: uni.$TIM.TYPES,
				empty_text: '没有找到相关记录',
				isEmpty: false,
				imgList: []
			}
		},
		computed: {
			lang() {
				return uni.getStorageSync('lang')
			}
		},
		onLoad(option) {
			this.conversationID = option.conversationID || '';
			this.groupID = option.groupID || 0;
			this.type = option.type || '';
			this.getGroupMemberInfo();
			let title = ''
			if(this.type === 'image') {
			  title = this.$t('chat.picture_video')
			}else {
				 title = this.$t('chat.file')
			}
			uni.setNavigationBarTitle({
			  title: title
			})
			setTimeout(()=> {
				uni.showLoading({
					title: this.$t('home.loading')
				})
			},500)
			this.getMessageList()
		},
		onNavigationBarButtonTap(e) {
			console.log(e)
			if(e.type == 'back') {
				uni.navigateBack()
			}
		},
	  methods: {
	  	handleAvatar,
	  	handleTextMessageShowContext,
	  	handleImageMessageShowContext,
	  	handleVideoMessageShowContext,
	  	handleAudioMessageShowContext,
	  	handleFileMessageShowContext,
	  	handleFaceMessageShowContext,
	  	handleLocationMessageShowContext,
	  	handleMergerMessageShowContext,
	  	handleTipMessageShowContext,
	  	handleCustomMessageShowContext,
	  	getHistoryChatTime,
	  	getGroupMemberInfo() {
	  		let that = this;
	  
	  		//从这获取本地头像姓名
	  		that.$http.get('/bbs/getUse/GroupImgAndId', {
	  			groupId: that.groupID
	  		}).then((res) => {
	  			that.groupMemberDict = res;
	  		}).catch(err => {})
	  	},
	  	handleUserAvatar(avatar, row) {
	  		console.log("row.from", row)
	  		if (this.groupMemberDict[row.from]) {
	  			console.log("this.groupMemberDict[row.from][1]", this.groupMemberDict[row.from][1])
	  			avatar = this.groupMemberDict[row.from][1];
	  		}
	  		return avatar;
	  	},
	  	async getMessageList() {
	  		let messageList = [];
	  		//获取本地缓存数据
	  		let storageMessage = [];
	  		storageMessage = await this.getStorageMsg();
	  		if (storageMessage.length) {
	  			messageList = [
	  				...storageMessage,
	  				...messageList
	  			];
	  
	  		}
	  
	  		//获取腾讯云 IM 数据
	  		let timMessageList = [];
	  		timMessageList = await this.getTimMsg(messageList);
	  		if (timMessageList.length) {
	  			messageList = [
	  				...timMessageList,
	  				...messageList
	  			];
	  		}
	  
	  		//获取 iDOCK消息 数据
	  		let iDOCKMessage = [];
	  		console.log("多了嘛", messageList)
	  		iDOCKMessage = await this.getIDOCKMsg(messageList);
	  		console.log("iDOCKMessage", iDOCKMessage)
	  		if (iDOCKMessage.length) {
	  			messageList = [
	  				...iDOCKMessage,
	  				...messageList
	  			];
	  		}
	  
	  
	  		this.list = messageList;
				console.log("ffffffffffffffffffffffffffffffff",this.list)
	  		this.messageList = messageList;
	  		this.list.sort((a, b) => {
	  			return b.time - a.time;
	  		})
	  		this.list.forEach(item => {
	  			item.flow = 'in'
	  		})
	  		
	  		console.log("this.keyword", this.keyword)
	  		console.log("this.current", this.current)
	  		
	  		console.log(this.list)
	  		if(this.type === 'image') {
	  			let searchList = [];
	  			searchList = this.messageList.filter(item => item.type === 'TIMImageElem' || item.type ===
	  				'TIMVideoFileElem');
	  			this.list = searchList;
					uni.hideLoading();
					for(var i in searchList){
						this.imgList.push(searchList[i].payload.imageInfoArray[0].url)  
					}
					console.log(this.imgList)
	  			console.log("searchList", this.list)
					if(this.list.length === 0) {
						this.isEmpty = true
					}
	  		}else {
	  			let searchList2 = [];
	  			searchList2 = this.messageList.filter(item => item.type === 'TIMSoundElem' || item.type ===
	  				'TIMFileElem');
	  			this.list = searchList2;
	  			console.log("文件的", this.list)
					uni.hideLoading();
					if(this.list.length === 0) {
						this.isEmpty = true
					}
	  		}
	  	
	  	},
	  	async getStorageMsg() {
	  
	  		let key_before = "uni-im-msg:" + this.conversationID
	  		let {
	  			keys,
	  			currentSize,
	  			limitSize
	  		} = uni.getStorageInfoSync()
	  		console.log("keys", keys);
	  
	  		keys = keys.filter(k => k.indexOf(key_before) === 0)
	  		if (keys.length == 0) {
	  			return []
	  		}
	  
	  		keys = keys.filter(k => k.indexOf(key_before) === 0)
	  		if (keys.length == 0) {
	  			return []
	  		}
	  		console.log("keys", keys);
	  
	  		let list = [];
	  		keys.forEach(key => {
	  
	  			let data = [];
	  			data = uni.getStorageSync(key) || [];
	  			list = [
	  				...data,
	  				...list,
	  			]
	  		})
	  
	  		return list;
	  	},
	  	async getTimMsg(messageList) {
	  
	  		let sequence = messageList[0].sequence || 0;
	  		let time = messageList[0].time || 0;
	  		let options = {
	  			conversationID: this.conversationID,
	  			count: 15,
	  		};
	  
	  		let data = [];
	  		data = await this.getTimServerMessage(options, [], messageList);
	  		console.log(" 腾讯云数据哦", data);
	  
	  		return data;
	  	},
	  	async getTimServerMessage(options, data = [], messageList) {
	  
	  
	  		let timMessageList = [];
	  		console.log("messageList", messageList)
	  		console.log("options", options)
	  		let imResponse = await uni.$TUIKit.getMessageList(options);
	  		console.log("imResponse", imResponse)
	  		timMessageList = imResponse.data.messageList || [];
	  		console.log("加完了", timMessageList)
	  		if (timMessageList.length) {
	  
	  			//检查腾讯云消息是否最新的
	  			let oldMessageTime = messageList[0].time;
	  			timMessageList = timMessageList.filter(item => item.time < oldMessageTime)
	  			console.log("oldMessageTime", oldMessageTime)
	  			console.log("timMessageList", timMessageList)
	  			if (timMessageList.length) {
	  				
	  				this.saveLocalCacheMessageList(timMessageList);
	  				
	  				data = [
	  					...timMessageList,
	  					...data,
	  				]
	  			}
	  		}
	  		console.log("加完了22", data)
	  
	  		//检查是否拉完
	  		console.log("继续了。。。1111", imResponse.data.isCompleted)
	  		if (imResponse.data.isCompleted) {
	  			console.log(" 弹奏了", data)
	  			return data;
	  		}
	  		console.log("继续了。。。2222")
	  
	  		//补充下条消息 ID
	  		if (imResponse.data.nextReqMessageID) {
	  			options.nextReqMessageID = imResponse.data.nextReqMessageID;
	  		}
	  		console.log("继续了。。。3333", options)
	  		return this.getTimServerMessage(options, data, messageList);
	  	},
	  	async getIDOCKMsg(messageList) {
	  
	  		let data = [];
	  		data = await this.getIDOCKServerMessage(data, messageList);
	  		console.log(" iDOCK 数据哦", data);
	  
	  		return data;
	  	},
	  	async getIDOCKServerMessage(data = [], messageList) {
	  
	  		//获取最新消息时间
	  		let lastMessageTime = 0;
	  		if (data.length > 0) {
	  			lastMessageTime = data[0].time;
	  		} else if (messageList.length > 0) {
	  			lastMessageTime = messageList[0].time;
	  		}
	  
	  		console.log("lastMessageTime", lastMessageTime)
	  		let iDOCKMessage = [];
	  		await httpInterceptor.get('/mgr/tim/chat/conversation/history/message', {
	  			conversation_id: this.conversationID,
	  			last_message_time: lastMessageTime
	  		}).then(res => {
	  			iDOCKMessage = res;
	  			if (res.length) {
	  				
	  				this.saveLocalCacheMessageList(res);
	  				data = [
	  					...res,
	  					...data,
	  				]
	  			}
	  		})
	  
	  		if (iDOCKMessage.length == 0) {
	  			console.log("直接退出拉")
	  			return data;
	  		}
	  
	  		return this.getIDOCKServerMessage(data, messageList);
	  	},
	  	async saveLocalCacheMessageList(data, isBefore = true) {
	  		// console.log("保存历史消息拉", data);
	  		// console.log("isBefore", isBefore);
	  		// console.log("this.store.conversationID", this.conversationID);
	  		// timStorage.insert([...data], isBefore, this.conversationID)
	  	},
	  },
	}	
</script>

<style lang="scss" scoped>
	.search {
		white-space: normal;
		word-break: break-all;
		margin-top: 60rpx;
		height: 100vh;
	}

	.search-result {
		height: 90vh;
		background-color: #fff;
		margin-top: 16rpx;
	}

	.search-header {
		padding: 30rpx;
	}

	.search-box {
		justify-content: space-between;
	}

	.search-input {
		padding: 0 10rpx 0 20rpx;
		border-radius: 16rpx;
		background-color: #fff;
		flex: 1;
		margin-left: 10rpx;
	}

	.cancel-btn {
		padding: 0 10rpx 0 28rpx;
		font-size: 32rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
		color: #3681C0;
	}

	.result-header {
		font-size: 28rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
		color: #8D8D8D;
		padding: 20rpx 0 20rpx 40rpx;
		background-color: #fff;
		border-bottom: 1px solid #eaedec;
	}

	.no-border {
		border: none
	}

	.t-conversation-item-container {
		width: 100%;
		padding: 20rpx 10rpx;
		background-color: #fff;

		.t-conversation-item {
			width: 100%;
			display: flex;

			.t-conversation-item-content {
				flex: 1;
				border-bottom: 2rpx solid #EEF0F3;

				.tui-result-name {
					font-size: 28rpx;
					font-family: Adobe Heiti Std;
					font-weight: normal;
					color: #868686;
				}

				.tui-result-time {
					font-size: 26rpx;
					color: #cdcdcd;
				}
			}
		}
	}

	.result-type {
		height: 100vh;
		background-color: #f1f1f1;
	}



	.avatar-box {
		position: relative;
		display: inline-flex;
	}

	.t-conversation-item-avatar {
		position: relative;
		width: 72rpx;
		height: 72rpx;
		border-radius: 16rpx;
		/*padding-left: 40rpx;*/
		/*padding-right: 24rpx;*/
		/*padding-bottom: 28rpx;*/
		/*padding-top: 28rpx;*/
		margin: 0 14rpx 0 28rpx;
		overflow: auto;
	}




	.tui-result-message {
		font-size: 27rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
		color: #98A0A1;
		line-height: 30rpx;
	}

	.more-chat-history {
		display: flex;
		justify-content: space-between;
		background-color: #fff;
		padding: 20rpx 28rpx 20rpx 36rpx;

		.more-chat-history-text {
			font-size: 28rpx;
			font-family: Adobe Heiti Std;
			font-weight: normal;
			color: #5B97C9;
			margin-left: 20rpx;
		}
	}
	.empty-wrap {
		position: fixed;
		top: 20%;
		left: 50%;
		transform: translate(-50%,-50%);
	}
</style>
